import logging
from ..mongodbconnection import mongorobot
from ..mongodbconnection import mongodbcon
from ..mysqlconn import conn
from ..memcachedconnection import memcachcon
import datetime
import json
import sys
import time

import requests as rs
from logging import getLogger

from chatterbot.zyrobot.decorators import time_statistic

s = rs.session()
s.keep_alive = False


web_logger = getLogger('web_logger')


# Globaltext = {}
# Globalvoice = {}


# 写入文本记录
def writetxtbig(file, text):
    # file_object = open(sys.path[0]+"/chatterbot/"+ file +"/" + time.strftime("%Y-%m-%d")+".txt", "a")
    file_object = open(sys.path[0] + "/chatterbot/" + file + "/" + 'big' + ".txt", "a")
    try:
        file_object.write("" + text + "\n")
    finally:
        file_object.close()


# 判断是否是引导的数据
def jugeguidancedata(cid, cmpid, text, sessionid, dbname):
    guidancedataid = getguidancedataid(cid, cmpid, dbname)
    # 是引导数据
    if len(guidancedataid) > 0:
        robotserviceid = guidancedataid[0]['robotserviceid']
        guidanceid = guidancedataid[0]['guidanceid']
        if text != '退出':

            # 插入引导数据
            updatacount = insertguidanceparamtext(robotserviceid, text, dbname, cid)
            # 查询新引导并返回
            if updatacount == 1:
                # 查询已存在的引导数
                guidanceinfoid = getguidancecount(robotserviceid, guidanceid, dbname, cid)
                return jugeguidancedataandbackresult(guidanceinfoid, robotserviceid, cid, cmpid, guidanceid, sessionid,
                                                     dbname)
            # 引导数据错误，重新返回引导数据
            else:
                guidanceinfo = getoldguidanceinfo(robotserviceid, dbname, cid)
                return backguidancequestion(guidanceinfo, cid, sessionid, dbname)
        else:
            return exitguidance(robotserviceid, cid, sessionid, dbname)

    return ''


# 退出引导
def exitguidance(robotserviceid, cid, sessionid, dbname):
    backcon = backguidanceinfo(1, cid, 8, 1, '退出成功！', '', '')
    sql = ' UPDATE zy_robot_serviceid set state=4 where robotserviceid=' + str(robotserviceid) + ' ;'
    updatacount = conn.mysql_updata(sql, dbname, cid)
    sufins = insertbackrecord(sessionid, 1, 16, backcon, dbname, cid)
    if updatacount == 1 and sufins == 1:
        return backcon
    else:
        return backguidanceinfo(1, cid, 8, 1, '退出失败！', '', '')


# 查询引导数据的编码
def getguidancedataid(cid, cmpid, dbname):
    sql = ' selecT s.robotserviceid,s.guidanceid from zy_robot_serviceid s  where s.state=1 and s.cmpid=' + str(
        cmpid) + ' and s.cid=' + str(cid) + ''
    guidancedataid = conn.mysql_seldic(sql, dbname, cid)
    return guidancedataid


# 查询现引导已存在多少项数据
def getguidancecount(robotserviceid, guidanceid, dbname, cid):
    sql = ' select COUNT(*) from zy_robot_service_text rst WHERE rst.robotserviceid=' + str(robotserviceid) + ''
    guidancecount = conn.mysql_selrowid(sql, dbname, cid)
    guidanceinfoid = selguidanceinfoid(guidanceid, guidancecount, guidancecount + 1, dbname, cid)
    return guidanceinfoid


# 根据编码查询图片信息
def selguidancephoto(cid, guidanceinfolistid, dbname):
    return backguidanceinfo(1, cid, 8, 3, '', guidancedetails(guidanceinfolistid, dbname, cid), '')


# 查询图片详情
def guidancedetails(guidanceinfolistid, dbname, cid):
    sql = ' select l.guidanceinfolistid,l.listname,l.Photoaddress,l.details,l.smevaluation from zy_guidance_list l where l.guidanceinfolistid=' + str(
        guidanceinfolistid) + '  '
    guidanceinfolist = conn.mysql_seldic(sql, dbname, cid)
    return guidanceinfolist


# 插入引导数据
def insertguidanceparamtext(robotserviceid, paramtext, dbname, cid):
    sql = 'select rst.guidanceinfoid from zy_robot_service_text rst where rst.robotserviceid=' + str(
        robotserviceid) + ' and rst.state=1 ORDER BY rst.id asc LIMIT 0,1'
    guidanceinfoid = conn.mysql_selrowid(sql, dbname, cid)
    sql = ' select gi.type from  zy_robot_guidanceinfo gi where gi.guidanceinfoid=' + str(guidanceinfoid) + ''
    guidancetype = conn.mysql_selrowid(sql, dbname, cid)
    updatacount = ''
    paramlistname = ''
    if guidancetype == 1:
        sql = 'UPDATE zy_robot_service_text set paramtext="' + str(
            paramtext) + '",state=2  where state=1 and robotserviceid=' + str(robotserviceid) + ' '
        updatacount = conn.mysql_updata(sql, dbname, cid)
    elif guidancetype == 2:
        sql = 'SELECT (case when gl.productid is null or  gl.productid="" then gl.listname else gl.productid end) as textcontext from zy_guidance_list gl where gl.guidanceinfoid=' + str(
            guidanceinfoid) + ' and gl.listname="' + str(paramtext) + '"'
        paramlistname = conn.mysql_selrowid(sql, dbname, cid)
    elif guidancetype == 3:
        sql = ' select (case when l.productid is null or  l.productid="" then l.listname else l.productid end) as textcontext from zy_guidance_list l where l.guidanceinfolistid="' + str(
            paramtext) + '" and l.guidanceinfoid=' + str(guidanceinfoid) + ' '
        paramlistname = conn.mysql_selrowid(sql, dbname, cid)
    if paramlistname != "":
        sql = 'UPDATE zy_robot_service_text set paramtext="' + str(
            paramlistname) + '",state=2  where state=1 and robotserviceid=' + str(robotserviceid) + ' '
        updatacount = conn.mysql_updata(sql, dbname, cid)
    return updatacount


# 查询是否存在引导
def jugeguidance(cmpid, text, cid, sessionid, dbname):
    # 判断库是否存在
    ifhavetable = mongodbcon.seltable('databaseguidance' + str(cmpid))
    if ifhavetable != 0:
        guidancedata = mongorobot.getguidance(cmpid, text, dbname)
        if guidancedata != '':
            guidanceid = guidancedata[1:]
            guitype = selguitype(guidanceid, dbname, cid)
            if guitype == 1:
                # 查询该引导是否曾经开启
                robotserviceid = guidanceifopen(cid, cmpid, guidanceid, dbname)
                if robotserviceid != "":
                    # 查询引导下一步要输入的内容
                    guidanceinfo = getoldguidanceinfo(robotserviceid, dbname, cid)
                    # 返引导提问
                    return backguidancequestion(guidanceinfo, cid, sessionid, dbname)
                # 开启新引导或新引导直接调用接口
                else:
                    return insertguidance(cid, cmpid, guidanceid, sessionid, dbname)
            else:
                return insertguidanceurl(cid, cmpid, guidanceid, sessionid, dbname)

    return ''


# 插入新引导记录并返回链接地址
def insertguidanceurl(cid, cmpid, guidanceid, sessionid, dbname):
    sql = ' INSERT into zy_robot_serviceid(cid,createtime,cmpid,guidanceid,guitype,state) VALUES (' + str(
        cid) + ',now(),' + str(cmpid) + ',' + str(guidanceid) + ',3); '
    robotserviceid = conn.mysql_insertid(sql, dbname, cid)
    # 查询引导第一个问题
    guiurl = selguidanceurl(guidanceid, dbname, cid)
    backcon = backguidanceinfo(1, cid, 8, 4, guiurl, '', '')
    # 插入返回数据
    sufins = insertbackrecord(sessionid, 1, 15, backcon, dbname, cid)
    if sufins == conn.err:
        return backtypeadd(0, cid, 1, "插入返回引导数据错误！", '')
    else:
        return backcon

    # 查询引导的链接


def selguidanceurl(guidanceid, dbname, cid):
    sql = 'select g.guidanceurl from zy_robot_guidance  g where g.guidanceid="' + str(guidanceid) + '" '
    guiurl = conn.mysql_selrowid(sql, dbname, cid)
    return guiurl


# 查询引导的类型
def selguitype(guidanceid, dbname, cid):
    sql = 'select g.guitype from zy_robot_guidance  g where g.guidanceid="' + str(guidanceid) + '" '
    guitype = conn.mysql_selrowid(sql, dbname, cid)
    return guitype


# 查询输入的提问内容
def backguidancequestion(guidanceinfo, cid, sessionid, dbname):
    if len(guidanceinfo) > 0:
        if guidanceinfo[0]['type'] == 2 or guidanceinfo[0]['type'] == 3:
            # 查询图片或list内容
            guidanceinfolist = guidancelist(guidanceinfo[0]['guidanceinfoid'], dbname, cid)
            backcon = backguidanceinfo(1, cid, 8, guidanceinfo[0]['type'], guidanceinfo[0]['guidanceinfoname'],
                                       guidanceinfolist, '')
        else:
            backcon = backguidanceinfo(1, cid, 8, guidanceinfo[0]['type'], guidanceinfo[0]['guidanceinfoname'], '', '')

        # 插入返回数据
        sufins = insertbackrecord(sessionid, 1, 14, backcon, dbname, cid)
        if sufins == conn.err:
            return backtypeadd(0, cid, 1, "插入返回引导数据错误！", '')
        else:
            return backcon

        # 插入新引导记录并返回提问


def insertguidance(cid, cmpid, guidanceid, sessionid, dbname):
    # 关闭以前的连接
    closesusse = updataotherstate(cid, '无', cmpid, '', dbname)
    if closesusse != "":
        sql = ' INSERT into zy_robot_serviceid(cid,createtime,cmpid,guidanceid) VALUES (' + str(cid) + ',now(),' + str(
            cmpid) + ',' + str(guidanceid) + '); '
        robotserviceid = conn.mysql_insertid(sql, dbname, cid)
        # 查询引导第一个问题
        guidanceinfoid = selguidanceinfoid(guidanceid, 0, 1, dbname, cid)
        return jugeguidancedataandbackresult(guidanceinfoid, robotserviceid, cid, cmpid, guidanceid, sessionid, dbname)
    else:
        return backtypeadd(0, cid, 1, '修改以前引导数据状态错误！', '')


# 查询是否有引导项并返回结果
def jugeguidancedataandbackresult(guidanceinfoid, robotserviceid, cid, cmpid, guidanceid, sessionid, dbname):
    # 判断是否有引导项
    if guidanceinfoid != "":
        # 插入数据
        sql2 = 'insert into zy_robot_service_text(robotserviceid,guidanceinfoid) VALUES (' + str(
            robotserviceid) + ',' + str(guidanceinfoid) + '); '
        insertcount = conn.mysql_insert(sql2, dbname, cid)
        if insertcount == 1:
            # 查询第一步的提问
            guidanceinfodaata = selguidanceinfo(guidanceinfoid, dbname, cid)
            # 返引导提问
            return backguidancequestion(guidanceinfodaata, cid, sessionid, dbname)
        else:
            return backtypeadd(0, cid, 1, "插入引导数据错误！", '')
    # 调用引导接口并完成引导
    else:
        return getuidanceurl(sessionid, guidanceid, robotserviceid, cmpid, cid, dbname)


# 调用引导接口
def getuidanceurl(sessionid, guidanceid, robotserviceid, cmpid, cid, dbname):
    sql = ' select CONCAT(g.guidanceurl,"?") from zy_robot_guidance g where g.guidanceid=' + str(guidanceid) + ' '
    guidanceurl = conn.mysql_selrowid(sql, dbname, cid)
    sqlparam = ' select GROUP_CONCAT(CONCAT(g.guidanceinfoParam,"=",rst.paramtext) SEPARATOR "&") from zy_robot_service_text rst,zy_robot_guidanceinfo g '
    sqlparam += ' where rst.robotserviceid=' + str(
        robotserviceid) + '  and g.guidanceinfoid=rst.guidanceinfoid ORDER BY thesequence asc '
    guidanceparam = conn.mysql_selrowid(sqlparam, dbname, cid)
    # 拼接url
    url = str(guidanceurl) + str(guidanceparam)
    # 调用接口返回json
    urljson = invokingurl(url)
    # 记录调用记录并修改机器人调用状态
    insersuss = updataguidancestate(url, cmpid, cid, guidanceid, robotserviceid, urljson, dbname)
    if insersuss == 1:
        backcon = backtypeadd(1, cid, 1, json.dumps(urljson, ensure_ascii=False), '')
    else:
        backcon = backtypeadd(1, cid, 1, '插入调用接口数据并修改引导完成状态错误！', '')
    sufins = insertbackrecord(sessionid, 1, 15, backcon, dbname, cid)
    if sufins == conn.err:
        return backtypeadd(0, cid, 1, "插入返回数据错误！", '')
    else:
        return backcon

    # 插入调用接口数据并修改引导完成状态


def updataguidancestate(url, cmpid, cid, guidanceid, robotserviceid, urljson, dbname):
    # 修改引导项完成的状态
    sql = ' UPDATE  zy_robot_serviceid set state=3 where robotserviceid=' + str(robotserviceid) + '; '
    # 插入调用引导数据
    sql += ' INSERT into zy_robot_guidance_url(cmpid,guidanceurl,cid,guidanceid,createtime,urljson,robotserviceid) VALUES'
    sql += ' (' + str(cmpid) + ',"' + str(url) + '", ' + str(cid) + ',' + str(guidanceid) + ',now(),"' + str(
        urljson) + '",' + str(robotserviceid) + ');'
    commit = conn.mysql_commit(sql, dbname, cid)
    return commit


# 调用接口
def invokingurl(url):
    req = rs.get(url)
    data = req.json()
    return data


# 查询引导数据
def selguidanceinfo(guidanceinfoid, dbname, cid):
    sql = ' select gi.type,gi.guidanceinfoname,gi.guidanceinfoid from zy_robot_guidanceinfo gi where gi.guidanceinfoid=' + str(
        guidanceinfoid) + '  '
    guidanceinfo = conn.mysql_seldic(sql, dbname, cid)
    return guidanceinfo


# 查询引导项
def selguidanceinfoid(guidanceid, beginnum, endnum, dbname, cid):
    sql1 = 'select gif.guidanceinfoid from zy_robot_guidanceinfo gif where gif.state=1 and gif.guidanceid=' + str(
        guidanceid) + ' ORDER BY gif.thesequence asc LIMIT ' + str(beginnum) + ',' + str(endnum) + ' '
    guidanceinfoid = conn.mysql_selrowid(sql1, dbname, cid)
    return guidanceinfoid


# 返回listjson
def backguidanceinfo(code, cid, backtype, guidancetype, guidanceinfoname, backanswer, choiceback):
    backtuple = {'code': str(code), 'cid': cid, 'backtype': str(backtype), 'guidancetype': str(guidancetype),
                 'backanswer': backanswer, 'guidanceinfoname': guidanceinfoname, 'choiceback': str(choiceback)}
    backcon = json.dumps(backtuple, ensure_ascii=False)
    web_logger.debug('backcon:%s', backcon)
    return backcon


# 查询图片或list内容
def guidancelist(guidanceinfoid, dbname, cid):
    sql = ' select l.guidanceinfolistid,l.listname,l.Photoaddress,l.details,l.smevaluation from zy_guidance_list l where l.guidanceinfoid=' + str(
        guidanceinfoid) + ' and l.state=1 ORDER BY l.thesequence asc  '
    guidanceinfolist = conn.mysql_seldic(sql, dbname, cid)
    return guidanceinfolist


# 查询曾经引导下一步要输入的内容
def getoldguidanceinfo(robotserviceid, dbname, cid):
    sql = 'select gi.type,gi.guidanceinfoname,gi.guidanceinfoid from zy_robot_guidanceinfo gi '
    sql += ' where gi.guidanceinfoid=(select st.guidanceinfoid from zy_robot_service_text st where st.robotserviceid=' + str(
        robotserviceid) + ' and st.state=1 ORDER BY id desc) '
    guidanceinfo = conn.mysql_seldic(sql, dbname, cid)
    return guidanceinfo


# 查询该引导是否开启
def guidanceifopen(cid, cmpid, guidanceid, dbname):
    sql = 'selecT s.robotserviceid from zy_robot_serviceid s  where s.cmpid=' + str(cmpid) + '  '
    if guidanceid != '':
        sql += ' and s.guidanceid=' + str(guidanceid) + ' '
    sql += ' and s.cid=' + str(cid) + ' and s.state not in (3,4) ORDER BY s.robotserviceid DESC LIMIT 0,1'
    robotserviceid = conn.mysql_selrowid(sql, dbname, cid)
    return updataotherstate(cid, robotserviceid, cmpid, '1', dbname)


# 将现在引用的引导设置为开启状态，其他为暂停状态1：未完成2：暂停3：已完成4：退出
def updataotherstate(cid, robotserviceid, cmpid, sqltype, dbname):
    sql1 = ' UPDATE zy_robot_serviceid set state=2  where state=1 and cid=' + str(cid) + '  and cmpid=' + str(
        cmpid) + ' '
    if sqltype == '1':
        sql1 += 'and robotserviceid!="' + str(
            robotserviceid) + '"; UPDATE zy_robot_serviceid set state=1 where  robotserviceid="' + str(
            robotserviceid) + '" and cmpid=' + str(cmpid) + ';'
    commit = conn.mysql_commit(sql1, dbname, cid)
    if commit == 1:
        return robotserviceid
    else:
        return ''


log = logging.getLogger('web_logger')


# 插入返回数据
def insertbackrecord(sessionid, code, answerFlag, answer, dbname, cid):
    sql = " insert into zy_robotanswer(sessionid,`CODE`,answerflag,Tdata,answer) VALUES \
           (" + str(sessionid) + "," + str(code) + "," + str(answerFlag) + ",NOW()," + json.dumps(answer,
                                                                                                  ensure_ascii=False) + "); "
    execount = conn.mysql_insert(sql, dbname, cid)
    return execount


# 插入返回数据（记录问题编码）
def insertbackrecordphone(sessionid, code, answerFlag, answer, answerid, dbname, cid):
    sql = " insert into zy_robotanswer(sessionid,`CODE`,answerflag,Tdata,answer,answerid) VALUES \
           ('" + str(sessionid) + "','" + str(code) + "','" + str(answerFlag) + "',NOW()," + json.dumps(answer,
                                                                                                        ensure_ascii=False) + " ,'" + str(
        answerid) + "' )"
    execount = conn.mysql_insert(sql, dbname, cid)
    return execount


# 返回json
def backtypeadd(code, cid, backtype, backanswer, choiceback):
    backtuple = {'code': str(code), 'cid': str(cid), 'backtype': str(backtype), 'backanswer': backanswer,
                 'choiceback': str(choiceback)}
    backcon = json.dumps(backtuple, ensure_ascii=False)
    web_logger.debug('backcon:%s', backcon)
    return backcon


def updata_sessionstorag(cid, type, num, session_data, session_sort, dbname):
    # 必须先查出来前面说的话，判断长度
    if session_data != "" and session_sort != "":
        select_aql = "select storagetext from zt_cmp_robot_sessionstorag where ifornotrobot = 2 and cid = '{}' and " \
                     "session_data = '{}' and session_sort = '{}' ORDER BY sessionstorageid desc limit 1".format(
                         str(cid),
                         str(session_data),
                         str(session_sort)
                     )
    else:
        select_aql = "select storagetext from zt_cmp_robot_sessionstorag where ifornotrobot = 2 and cid = '{}' and " \
                     "session_data = '{}' and session_sort = '{}' ORDER BY sessionstorageid desc limit 1".format(
                         str(cid),
                         "",
                         str(session_sort)
                     )

    storagetext = conn.mysql_selrowid(select_aql, dbname, cid)
    print("******************************88storagetext***********************************")
    print(storagetext)
    print("******************************************************************************")

    ######  更新操作 ##############
    print("&&&&&&&&")
    print(type, num)
    print("&&&&&&&&")

    updatasql = "UPDATE zt_cmp_robot_sessionstorag set type='" + str(type) + "',num='" + str(num) + "' " \
                                                                                                    "where ifornotrobot=2 and cid='" + str(
        cid) + "'   "
    if session_data != "" and session_sort != "":
        updatasql += " and session_data='" + str(session_data) + "' and session_sort='" + str(session_sort) + "'"
    else:
        updatasql += " and session_data='' and session_sort='" + str(session_sort) + "'"
    updatasql += " ORDER BY sessionstorageid desc  limit 1"
    cont = conn.mysql_updata(updatasql, dbname, cid)


@time_statistic(4, 'cid')
def insertsessionstorage(ifornotrobot, storagetext, storagevoice, createtime, cid, operation, session_data,
                         session_sort, peplesex, answertype, num, dbname, askid):
    # if str(ifornotrobot)==str(2):
    # updatasql = "UPDATE zt_cmp_robot_sessionstorag set type='"+str(type)+"',num='"+str(num)+"' " \
    #             "where ifornotrobot=2 and cid='"+str(cid)+"' ORDER BY createtime desc  limit 1"
    # cont = conn.mysql_updata(updatasql)
    # print('sql',sql)
    sql = "insert into zt_cmp_robot_sessionstorag(ifornotrobot,storagetext,storagevoice,createtime,cid,session_data,session_sort,type,num,askid) VALUES" \
          " ('" + str(ifornotrobot) + "','" + str(storagetext) + "','" + str(storagevoice) + "','" + str(
              createtime) + "','" + str(cid) + "','" + str(session_data) + "','" + str(session_sort) + "','" + str(
              answertype) + "','" + str(num) + "','" + str(askid) + "')"
    insertcount = conn.mysql_insert(sql, dbname, cid)

    return insertcount


# 删除多余的会话
def del_excess_data(session_data, session_sort, cid, dbname):
    sql = "DELETE from zt_know_ask where cid='" + str(cid) + "' and session_data='" + str(
        session_data) + "' and session_sort<" + str(session_sort) + ";"
    conn.mysql_updata(sql, dbname, cid)
    sql = "DELETE from zt_cmp_robot_respond where  cid='" + str(cid) + "' and session_data='" + str(
        session_data) + "' and session_sort<" + str(session_sort) + ";"
    conn.mysql_updata(sql, dbname, cid)
    # sql = "DELETE from zt_cmp_robot_sessionscene where  cid='"+str(cid)+"' and session_data='"+str(session_data)+"' and session_sort<"+str(session_sort)+";"
    # conn.mysql_updata(sql)
    sql = "DELETE from zt_cmp_robot_sessionstorag where  cid='" + str(cid) + "' and session_data='" + str(
        session_data) + "' and session_sort<" + str(session_sort) + ";"
    conn.mysql_updata(sql, dbname, cid)
    sql = "DELETE from zt_customer_attr_link where   saleid='" + str(cid) + "' and session_data='" + str(
        session_data) + "' and session_sort<" + str(session_sort) + ";"
    conn.mysql_updata(sql, dbname, cid)


# 调用TTS获取录音地址
@time_statistic(2, 'cid')
def get_TTS_voice_address(TTSIP, text, cid, speed, voice, datatype, platformtype, pitch_rate, informant):
    try:
        url = "http://" + str(TTSIP) + "/createTTSaddress?text=" + str(text) + "&cid=" + str(cid) + "&speed=" + str(
            speed) + "&voice=" + str(
            voice) + "&datatype=" + str(datatype) + "&platformtype=" + str(platformtype) + "&pitch_rate=" + str(
            pitch_rate) + "&informant=" + str(informant) + ""
        req = rs.get(url)
        adress = req.text
        return adress
    except Exception as e:
        web_logger.error('cid:%s error:%s %s', cid, type(e), e)
        return ''


# 返回json
@time_statistic(1, 'cid')
def backtypeaddphone(code, cid, backtype, backanswer, choiceback, conversation, HoodleMobileid, operation, serviceid,
                     attach, instructid, memo, attitude, helloorbye, woeid, phone, waitingtime, pipetype, num,
                     session_data, session_sort, dbname):
    memisagree = memcachcon.if_exist(str(dbname) + 'isagree' + str(cid))
    memcloseresult = memcachcon.if_exist(str(dbname) + 'closeresult' + str(cid))
    # print('memcloseresult',memcloseresult)
    memistransfer = memcachcon.if_exist(str(dbname) + 'istransfer' + str(cid))
    isagree = ''
    closeresult = ''
    istransfer = ''
    if memisagree != None:
        isagree = memisagree
        memcachcon.del_cach(str(dbname) + 'isagree' + str(cid))
    if memcloseresult != None:
        closeresult = memcloseresult
        memcachcon.del_cach(str(dbname) + 'closeresult' + str(cid))
    if memistransfer != None:
        istransfer = memistransfer
    if memo == None:
        memo = ''
    if waitingtime != '2':
        waitingtime = '8'
    if memo != "":
        if "\xa0" in str(memo):
            memo = memo.replace("\xa0", '')
    if str(backtype) == '1' and str(instructid) != '4' and str(instructid) != '7' and str(instructid) != '3' and str(
            code) != '-1' and str(operation) != '8':
        voice = memcachcon.if_exist(str(dbname) + 'TTS_voice' + str(cid))
        speed = memcachcon.if_exist(str(dbname) + 'TTS_speed' + str(cid))  # 语速
        platformtype = memcachcon.if_exist(str(dbname) + 'TTS_informantid' + str(cid))  # TTS平台
        informant = memcachcon.if_exist(str(dbname) + 'TTS_remark' + str(cid))  # 说话人
        voice_dress = ''
        if backanswer != "":
            voice_dress = get_TTS_voice_address(conn.TTSIP, backanswer, cid, speed, voice, '', platformtype, 0,
                                                informant)
        memo = backanswer
        backanswer = voice_dress
        backtype = 9
        web_logger.debug('cid:%s memo:%s', cid, memo)
    elif str(backtype) == '1' and (str(instructid) == '4' or str(instructid) == '7'):
        backtype = 9
        memo = backanswer
        backanswer = ''

    backtuple = {'code': str(code), 'cid': str(cid), 'backtype': str(backtype), 'backanswer': backanswer,
                 'choiceback': str(choiceback), 'conversation': str(conversation),
                 'questionid': str(HoodleMobileid), 'operation': str(operation),
                 'serviceid': str(serviceid), 'instructid': str(instructid), 'attach': str(attach),
                 'memo': str(memo), 'attitude': str(attitude), 'interrupt': str(helloorbye), 'collectid': str(woeid),
                 'phone': str(phone), 'waitingtime': str(waitingtime), 'type': str(pipetype), 'num': str(num),
                 'session_data': str(session_data), 'session_sort': str(session_sort),
                 'isagree': str(isagree), 'closeresult': str(closeresult), 'istransfer': str(istransfer)
                 }
    backcon = json.dumps(backtuple, ensure_ascii=False, sort_keys=True)

    if str(operation) != '6' and str(operation) != '7':
        # 插入数据
        if str(operation) == '1' or str(operation) == '3' or str(operation) == '4' or str(operation) == '5' or str(
                operation) == '14' or str(operation) == '9':
            if str(operation) == '5' or str(operation) == '9':
                if str(instructid) == '4':
                    updata_sessionstorag(cid, 4, '1', session_data, session_sort, dbname)
            if str(instructid) != '3' and str(instructid) != '4':
                if str(instructid) == '2' and str(backanswer) == '等待':
                    pass
                else:
                    if pipetype != "":  # and  str(operation)!='4' :
                        updata_sessionstorag(cid, pipetype, num, session_data, session_sort, dbname)
                    if str(instructid) != '4' and str(instructid) != '7':
                        if str(backtype) == '1':
                            insertsessionstorage(1, backanswer, '',
                                                 datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), cid, operation,
                                                 session_data, session_sort, '', '', '', dbname, HoodleMobileid)
                        else:
                            insertsessionstorage(1, memo, backanswer,
                                                 datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), cid, operation,
                                                 session_data, session_sort, '', '', '', dbname, HoodleMobileid)

        memsession_data = memcachcon.if_exist(str(dbname) + 'Globalsessiondata' + str(cid))
        memsession_sort = memcachcon.if_exist(str(dbname) + 'Globalsessionsort' + str(cid))

        if memsession_data != '' and memsession_data != None and memsession_sort != None and memsession_sort != '':
            if str(memsession_sort) != '1':
                del_excess_data(memsession_data, memsession_sort, cid, dbname)

    web_logger.debug('cid:%s backcon:%s', cid, backcon)
    return backcon


def backresult(result):
    backtuple = {'result': str(result)}
    backcon = json.dumps(backtuple, ensure_ascii=False)
    return backcon


# 查询无法回答的问题的录音
def backunknowvoice(cmpid, serviceid, num, dbname, cid):
    adress = ''
    if num == 1:
        sql = "select r.unknowanswer,r.vtype,r.unknowanswertext from zt_cmp_robot r where r.cmpid='" + str(
            cmpid) + "' and r.onserviceid='" + str(serviceid) + "' "
    else:
        sql = "select r.unknowagain,r.vtype,r.unknowagaintext from zt_cmp_robot r where r.cmpid='" + str(
            cmpid) + "' and r.onserviceid='" + str(serviceid) + "' "
    adress = conn.mysql_sel(sql, dbname, cid)

    return adress
